#!/usr/bin/env python
# Generate configurations for web3 sites
import os
from string import Template

def which_tech(tech='wordpress'): 
    if '1.3.5' in tech: return 'cs-cart-1'
    elif '2.X' in tech: return 'cs-cart-2'
    elif 'wordpress' in tech: return 'wordpress'
    elif 'solo' in tech: return 'solo_magento'
    elif 'magento' in tech: return 'magento'
    else: return 'notech'

def server(name='domain.com', ip='1.2.3.4', tech='WordPress'): 
    return Template("""## $tech configuration for $name
server {
    server_name .$name; 
    listen $ip:80;""").substitute(name=name, ip=ip, tech=tech)

def certs(name='domain.com', ip='1.2.3.4'): 
    cert_dir = '/etc/ssl/certs/'
    key_dir = '/etc/ssl/private/'

    if os.path.isfile('/etc/ssl/certs/' + name + '.crt'): 
        cert_dir += name + '.crt'
        key_dir += name + '.key'
    elif os.path.isfile('/etc/ssl/certs/www.' + name + '.crt'):  
        cert_dir += 'www.' + name + '.crt'
        key_dir += 'www.' + name + '.key'
    else: 
        return ''

    add = Template("""    listen $ip:443 ssl; 

    ssl_certificate $cert_dir; 
    ssl_certificate_key $key_dir;
""")
 
    return add.substitute(ip=ip, cert_dir=cert_dir, key_dir=key_dir)

def logs(name='domain.com'): 
    return Template("""    access_log /var/log/nginx/$name.access_log main; 
    error_log /var/log/nginx/$name.error_log;""").substitute(name=name) 

def root(name='domain.com'): 
    if name.count('.') > 1: 
        subdomain, domain, tld = name.split('.')
        return '    root /var/www/vhosts/%s.%s/subdomains/%s/httpdocs;' % (domain, tld, subdomain) 
    else: 
        return '    root /var/www/vhosts/%s/www;' % name 

def fcgi(name='domain.com', doc_root='/var/www', tech='wordpress'): 
    if 'm' == tech[0]: 
        return """    include inc/magento.conf; 
    location ~ \.php$ {
        include fastcgi.conf;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param PHP_ADMIN_VALUE "open_basedir=/home/secmagef/public_html:%s/app:/tmp";
    }""" % doc_root.split()[-1][:-1] # this nonsense is from laziness
    else: 
        return '    include inc/%s.conf;\n    include inc/php.conf;' % tech.replace('solo_', '')

def conf(name='domain.com', ip='1.2.3.4', ssl='\n', tech='wordpress'): 
    doc_root = root(name)
    params = fcgi(name, doc_root, tech)
    if ssl == 1:
        ssl = certs(name, ip)
    
    log_files = logs(name)

    serv_conf = server(name, ip, tech)
    
    conf = Template("""$serv_conf
$ssl
$log_files

$doc_root

$params
}""")  
    return conf.substitute(name=name, ip=ip, ssl=ssl, log_files=log_files, serv_conf=serv_conf, tech=tech, doc_root=doc_root, params=params); 

if __name__ == '__main__': 
# Columns
# site technology ssl basedir notes ip

# Notes
# not all sites have basedir or notes => use [-1] for IP

    file = open('sites.txt'); f = file.read().splitlines() ; file.close()

    holder = {}
    for each in f: 
        each = each.split('\t')
        site, tech, ip = each[:3]
        ssl = '' 
        if '1' in each[3]: ssl = 1
        tech = which_tech(tech)

        holder[site] = {
            'name': site, 
            'tech': tech, 
            'ip'  : ip,
            'ssl' : ssl 
        }
    for each in holder.keys(): 
    #for each in holder.keys()[:5]: 
        name = holder[each]['name']
        tech = holder[each]['tech']
        ip = holder[each]['ip']
        ssl = holder[each]['ssl']
        
        f = '%s.conf' % name
        config = conf(name, ip, ssl, tech)
        print config
        f = open('sites/' + f, 'w')
        f.write(config)
        f.close()

